package core

import (
	"compress/gzip"
	"github.com/json-iterator/go"
	"log"
	"os"
	"path/filepath"
)

const (
	ACTION_INSERT  = 0x00
	ACTION_UPDATE  = 0x01
	ACTION_DELETE  = 0x02
	ACTION_SET     = 0x03
	ACTION_DROP_DB = 0x04

	ACTION_CHECK_LOG = 0x03
)

type DBLog struct {
	DbName         string
	CollectionName string
	Action         uint
	Value          interface{}
}

func InitStorage() error {
	if !exists(DBPath) {
		err := os.MkdirAll(DBPath, 0755)
		if err != nil {
			log.Fatal("创建数据库文件夹错误")
		}
	}
	return Restore()
}

/**
通过全量和增量备份还原数据库
全量：一次性还原所有
增量: 在全量的基础上还原
*/
func Restore() error {
	globalMutex.Lock()
	defer globalMutex.Unlock()
	fi, err := os.Open(filepath.Join(DBPath, "db"))
	if err != nil {
		return err
	}
	reader, err := gzip.NewReader(fi)
	defer reader.Close()
	if err != nil {
		return err
	}
	err = jsoniter.NewDecoder(reader).Decode(&qiuya.Collections)
	return err
}

func Snapshot(lock bool) error {
	if lock {
		globalMutex.Lock()
		defer globalMutex.Unlock()
	}

	fw, err := os.Create(filepath.Join(DBPath, "db")) // 创建gzip包文件，返回*io.Writer
	if err != nil {
		return err
	}
	defer fw.Close()

	var writer = gzip.NewWriter(fw)
	defer writer.Close()

	err = jsoniter.NewEncoder(writer).Encode(qiuya.Collections)
	return err
}

func exists(file string) bool {
	_, err := os.Stat(file)
	return err == nil
}
